import { onBeforeUnmount, onMounted } from 'vue'
import Emitter from '@/utils/EventBus'
import { throttle } from '@/utils/tool'
import type { Ref } from 'vue-demi'

export const useMainScroll = <T extends Element>(refValue: Ref<T>): void => {
  onMounted(() => {
    Emitter.on('scrollToTop', handleScrollToTop)
    refValue.value.addEventListener('scroll', throttle(handleMainScroll, 100))
  })

  onBeforeUnmount(() => {
    Emitter.emit('mainScroll')
    Emitter.off('scrollToTop', handleScrollToTop)
    refValue.value.removeEventListener('scroll', handleMainScroll)
  })
  const handleScrollToTop = (scrollTop: number) => {
    refValue.value.scrollTop = scrollTop
  }
  const handleMainScroll = () => {
    Emitter.emit('mainScroll', refValue.value)
  }
}
